import request from '../until/request.ts';

export interface Filters {
    id: number;
    name: string;
 
  }
  export interface CourseItem {
    name: string;
    id: number;
   
    introduction: string;
    videoURL: string;
    imageURL: string;
    writer: string;  
  }
  interface BackResponse<T> {
    code: number;
    data: T;
    message: string;
    isOk: boolean;
    msg: string;
  }
  export const getCourseList = async (): Promise<CourseItem[]> => {
    const response = await request.get<BackResponse<CourseItem[]>>('/course/list');
    if (response.data.code === 0||response.data.isOk === true) {
      return response.data.data; // 返回会议列表数据
    } else {
      throw new Error(response.data.message || '获取课程列表失败');
    }
  };
  export const addCourseService = async (course: CourseItem): Promise<BackResponse<string>> => {
    const response = await request.post<BackResponse<string>>('/course/add', course);
    return response.data; // 返回消息
  }
  export const editCourseService = async (course: CourseItem): Promise<void> => {
    const response = await request.post<BackResponse<void>>('/course/update', course);
    
    if (response.data.code !== 0) {
      throw new Error(response.data.message || '编辑课程失败');
    }
  }
  export const deleteCourseService = async(course: CourseItem): Promise<BackResponse<string>>=> {
    
    const response = await request.post<BackResponse<string>>('/course/deleteById', course);
    return response.data; // 返回消息
  }
  export const searchCourseService = async (course: Filters): Promise<CourseItem[]> => {
    const response = await request.post<BackResponse<CourseItem[]>>('/course/search', course);
    if (response.data.code === 0) {
      return response.data.data; // 返回列表数据
    } else {
      throw new Error(response.data.message || '获取新闻列表失败');
    }
  }
  export const exportFile = async (): Promise<void> => {
    try {
      const response = await request({
        url: '/export/course',
        method: 'GET',
        responseType: 'blob',  // 重要：确保响应类型为 'blob'
      });
  
      // 创建一个下载链接并模拟点击，从而实现文件下载
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'Course.xlsx');  // 为下载的文件指定默认文件名
      document.body.appendChild(link);
      link.click();
  
      // 清理创建的URL和链接元素
      link.parentNode.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
      throw new Error('导出失败');
    }
    }